/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.samples.ohos;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;

import java.util.ArrayList;
import java.util.List;

import io.sentry.ISpan;
import io.sentry.Sentry;
import io.sentry.SpanStatus;
import io.sentry.ohos.okhttp.SentryOkHttpInterceptor;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * SecondAbility
 *
 * @since 2021-06-02
 */
public class SecondAbility extends Ability {
    /**
     * base url
     */
    public static final String BASE_URL = "https://api.github.com/";
    private List<Repo> repos;
    private OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new SentryOkHttpInterceptor()).build();
    private Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
    private GitHubService service = retrofit.create(GitHubService.class);

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_second);
        getWindow().setStatusBarColor(Color.getIntColor("#006666"));
        Text title = (Text) findComponentById(ResourceTable.Id_txt_title);
        title.setFont(Font.DEFAULT_BOLD);
        ISpan activeSpan = Sentry.getSpan();
        ISpan span = null;
        if (activeSpan != null) {
            span = activeSpan.startChild("onStart", getClass().getSimpleName());
        }
        findComponentById(ResourceTable.Id_do_request).setClickedListener(component -> {
            updateRepos();
        });
        findComponentById(ResourceTable.Id_back_main).setClickedListener(component -> {
            terminateAbility();
            Intent intent2 = new Intent();
            Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(MainAbility.class)
                .build();
            intent2.setOperation(operation);
            startAbility(intent2);
        });
        if (span != null) {
            span.finish(SpanStatus.OK);
        }
    }

    private void showText(boolean visible, String text) {
        Text text2 = (Text) findComponentById(ResourceTable.Id_text);
        text2.setText(visible ? text : "");
        ProgressBar progressBar = (ProgressBar) findComponentById(ResourceTable.Id_indeterminateBar);
        progressBar.setIndeterminate(true);
        progressBar.setProgressColor(new Color(Color.getIntColor("#FF0000")));
        if (visible) {
            progressBar.setVisibility(Component.HIDE);
            text2.setVisibility(Component.VISIBLE);
        } else {
            progressBar.setVisibility(Component.VISIBLE);
            text2.setVisibility(Component.HIDE);
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        ISpan span = Sentry.getSpan();
        if (span != null) {
            span.startChild("onActive", getClass().getSimpleName());
        }
        updateRepos();
        if (span != null) {
            span.finish(SpanStatus.OK);
        }
    }

    private void updateRepos() {
        showText(false, "");
        ISpan currentSpan = Sentry.getSpan();
        ISpan span;
        if (currentSpan != null) {
            span = currentSpan.startChild("updateRepos", getClass().getSimpleName());
        } else {
            span = Sentry.startTransaction("updateRepos", "task");
        }

        final ISpan tempSpan = span;
        TextField textField = (TextField) findComponentById(ResourceTable.Id_edit_repo);
        service.listRepos(textField.getText()).enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
                repos = response.body();
                if (repos == null) {
                    repos = new ArrayList<>();
                }
                tempSpan.finish(SpanStatus.OK);
                showText(true, "items:" + repos.size());
                ISpan transaction = Sentry.getSpan();
                if (transaction != null) {
                    transaction.finish(SpanStatus.OK);
                }
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable throwable) {
                tempSpan.finish(SpanStatus.INTERNAL_ERROR);
                Sentry.captureException(throwable);
                showText(true, "error: " + throwable.getMessage());
                ISpan transaction = Sentry.getSpan();
                if (transaction != null) {
                    transaction.finish(SpanStatus.INTERNAL_ERROR);
                }
            }
        });
    }
}
